package controllers

import (
	"day2zk/models"
	beego "github.com/beego/beego/v2/server/web"
)

type WWW struct {
	beego.Controller
}
type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (w *WWW) Add() {
	bos := w.GetString("bos")
	nie := w.GetString("nie")
	times := w.GetString("times")
	zuo := w.GetString("zuo")
	if bos == "" || nie == "" || times == "" || zuo == "" {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "标题,内容,时间,作者不能为空",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	ww := models.Books{
		Bos:   bos,
		Nie:   nie,
		Times: times,
		Zuo:   zuo,
	}
	err := models.DB.Create(&ww).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Data: ww,
		}
		w.ServeJSON()
	}
}

func (w *WWW) List() {
	page, _ := w.GetInt("page", 1)
	size, _ := w.GetInt("size", 5)
	offset := (page - 1) * size
	var count int64
	var boos []models.Books
	models.DB.Model(&models.Books{}).Count(&count)
	err := models.DB.Offset(offset).Limit(size).Find(&boos).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "分页失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		pageDate := make(map[string]interface{})
		pageDate["count"] = count
		pageDate["boos"] = boos
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "分页成功",
			Data: pageDate,
		}
		w.ServeJSON()
	}
}
